package com.ys.controller.api.outer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ys.entity.amazonorder.*;
import com.ys.entity.base.*;
import com.ys.entity.business.*;
import com.ys.entity.finance.TcwCapitalBusinessCost;
import com.ys.entity.flow.YspModel;
import com.ys.entity.purchase.TcgPurchaseByOrder;
import com.ys.entity.storage.TccAssemblyMaintain;
import com.ys.entity.storage.TccFbaBoxUpItem;
import com.ys.entity.storage.TccFbaPlanItem;
import com.ys.entity.sys.YsMenu;
import com.ys.enume.base.TsBatchImportLogEnum;
import com.ys.enume.business.TpProductMaterialEnum;
import com.ys.mapper.base.TbUserMonthPerformanceMapper;
import com.ys.mapper.base.TbUserPaySlipMapper;
import com.ys.mapper.business.TpProductActiveMapper;
import com.ys.mapper.business.TpProductBasisMapper;
import com.ys.mapper.business.TpProductMaterialMapper;
import com.ys.mapper.storage.TccFbaBoxUpItemMapper;
import com.ys.service.bi.BiClassifyModuleService;
import com.ys.service.bi.BiFlowAnalysisService;
import com.ys.service.finance.TcwWanliDrawingService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.purchase.TcgPurchaseByOrderService;
import com.ys.service.report.TcoBusinessDataStatService;
import com.ys.util.RandomUtil;
import com.ys.util.shiro.ShiroUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.config.MyConfig;
import com.ys.entity.eKnowAi.EKnowKnowledgeList;
import com.ys.entity.eKnowAi.EKnowTimerSet;
import com.ys.entity.finance.TcwAccountDetailedForCompany;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.hr.ThrUserArchives;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.TsUserInfo;
import com.ys.mapper.base.TbUserPersonalTaxCountMapper;
import com.ys.mapper.hr.ThrOperateCompanyApplyMapper;
import com.ys.mapper.sys.TsUserInfoMapper;
import com.ys.service.amazonorder.TcoRankShopByAmountRmbService;
import com.ys.service.base.TbBaseInfoAreaService;
import com.ys.service.base.TbUserJobLevelManageService;
import com.ys.service.base.TbUserPayApplyService;
import com.ys.service.base.TbUserPaySlipService;
import com.ys.service.business.TcwAccountDetailedForCompanyService;
import com.ys.service.business.TpAmazonShopProductCountService;
import com.ys.service.business.TpAnalysisDailyTargetService;
import com.ys.service.business.TpAnalysisDailyTargetSetService;
import com.ys.service.business.TpBoutiqueService;
import com.ys.service.business.TpShopAnalysisReportFormsService;
import com.ys.service.eKnowAi.EKnowKnowledgeListService;
import com.ys.service.eKnowAi.EKnowTimerSetService;
import com.ys.service.hr.ThrUserArchivesService;
import com.ys.service.report.ReDeptRevenueExpenditureService;
import com.ys.service.report.ReFinanceExamineService;
import com.ys.util.DateUtil;
import com.ys.util.RedisUtil;
import com.ys.util.baidu.ApiHttpClientUtils;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/outer/apiOuterDemoLzm")
public class ApiOuterDemoLzmController {

    private static final Logger logger = LoggerFactory.getLogger(ApiOuterDemoLzmController.class);

	private static String URLAPI2_0 = MyConfig.getUrlApi1_5();

    @Autowired
	private TpShopAnalysisReportFormsService tpShopAnalysisReportFormsService;
	@Autowired
	private TpAmazonShopProductCountService tpAmazonShopProductCountService;
	@Autowired
	private TpAnalysisDailyTargetSetService tpAnalysisDailyTargetSetService;

	@Autowired
	private TpAnalysisDailyTargetService tpAnalysisDailyTargetService;
	@Autowired
	private EKnowKnowledgeListService eKnowKnowledgeListService;

	@Autowired
	private EKnowTimerSetService eKnowTimerSetService;

	@Autowired
	private ReFinanceExamineService reFinanceExamineService;


	@Autowired
	private ReDeptRevenueExpenditureService reDeptRevenueExpenditureService;

	@Autowired
	private TpBoutiqueService tpBoutiqueService;

	@Autowired
	private ApiHttpClientUtils apiHttpUtils;

	//@Autowired
	//private TpBoutiqueService tpBoutiqueService;

	@Autowired
	private TcoRankShopByAmountRmbService tcoRankShopByAmountRmbService;

    @Autowired
    private TbBaseInfoAreaService tbBaseInfoAreaService;

	@Autowired
	private TcgPurchaseByOrderService tcgPurchaseByOrderService;


	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private ThrUserArchivesService thrUserArchivesService;

	@Autowired
	private ThrOperateCompanyApplyMapper thrOperateCompanyApplyMapper;

	@Autowired
	private TsUserInfoMapper tsUserInfoMapper;

	@Autowired
	private TbUserJobLevelManageService tbUserJobLevelManageService;

	@Autowired
	private TbUserPaySlipService tbUserPaySlipService;

	@Autowired
	private TbUserPayApplyService tbUserPayApplyService;


	@Autowired
	private TbUserPersonalTaxCountMapper tbUserPersonalTaxCountMapper;

	@Autowired
	private TcwAccountDetailedForCompanyService tcwAccountDetailedForCompanyService;

	@Autowired
	private BiClassifyModuleService biClassifyModuleService;
	@Autowired
	private BiFlowAnalysisService biFlowAnalysisService;


	@Autowired
	private TbUserPaySlipMapper tbUserPaySlipMapper;


	@Autowired
	private YspTaskService yspTaskService;


	@Autowired
	private TbUserMonthPerformanceMapper tbUserMonthPerformanceMapper;



	@Autowired
	private TcwWanliDrawingService tcwWanliDrawingService;



	@Autowired
	private TcoBusinessDataStatService tcoBusinessDataStatService;


	@Autowired
	private TpProductMaterialMapper tpProductMaterialMapper;

	@Autowired
	private TpProductActiveMapper tpProductActiveMapper;

	@Autowired
	private TpProductBasisMapper tpProductBasisMapper;

	@Autowired
	private TccFbaBoxUpItemMapper tccFbaBoxUpItemMapper;


	/**
	 * 手动刷新店铺运营表数据
	 */
	@RequestMapping("/test1")
    @ResponseBody
	public R test1(HttpServletRequest request, HttpServletResponse response
			) {
		try {
			addtpShopAnalysisReportFormsService("2024-06");
			return R.ok();
		}catch (Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
			return R.error("操作失败!");
		}
	}

	public void addtpShopAnalysisReportFormsService(String infoTime){
		logger.info("*************开始刷新店铺运营表数据*************");
		logger.info("开始删除店铺运营表数据");
		tpShopAnalysisReportFormsService.delByInfoTime(infoTime);
		logger.info("删除完毕，开始刷新店铺运营表数据");
		tpShopAnalysisReportFormsService.add(infoTime);
		//统计上个月的运营分析表数据，总和
		tpShopAnalysisReportFormsService.addTotal(infoTime);
		logger.info("*************完成刷新店铺运营表数据*************");
	}



	/**
	 * 手动刷新店铺运营表数据
	 */
	@RequestMapping("/testAll1")
	@ResponseBody
	public R testAll1(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			tpShopAnalysisReportFormsService.delByInfoTime("2023-01");
			tpShopAnalysisReportFormsService.delByInfoTime("2023-02");
			tpShopAnalysisReportFormsService.delByInfoTime("2023-03");
			tpShopAnalysisReportFormsService.delByInfoTime("2023-04");
			tpShopAnalysisReportFormsService.delByInfoTime("2023-05");
			tpShopAnalysisReportFormsService.delByInfoTime("2023-06");
			tpShopAnalysisReportFormsService.delByInfoTime("2023-07");
			tpShopAnalysisReportFormsService.delByInfoTime("2023-08");
			tpShopAnalysisReportFormsService.delByInfoTime("2023-09");
			tpShopAnalysisReportFormsService.delByInfoTime("2023-10");
			tpShopAnalysisReportFormsService.delByInfoTime("2023-11");
			tpShopAnalysisReportFormsService.delByInfoTime("2023-12");
			logger.info("*************开始刷新2023-01店铺运营表数据*************");
			addtpShopAnalysisReportFormsService("2023-01");
			logger.info("*************开始刷新2023-02店铺运营表数据*************");
			addtpShopAnalysisReportFormsService("2023-02");
			logger.info("*************开始刷新2023-03店铺运营表数据*************");
			addtpShopAnalysisReportFormsService("2023-03");
			logger.info("*************开始刷新2023-04店铺运营表数据*************");
			addtpShopAnalysisReportFormsService("2023-04");
			logger.info("*************开始刷新2023-05店铺运营表数据*************");
			addtpShopAnalysisReportFormsService("2023-05");
			logger.info("*************开始刷新2023-06店铺运营表数据*************");
			addtpShopAnalysisReportFormsService("2023-06");
			logger.info("*************开始刷新2023-07店铺运营表数据*************");
			addtpShopAnalysisReportFormsService("2023-07");
			logger.info("*************开始刷新2023-08店铺运营表数据*************");
			addtpShopAnalysisReportFormsService("2023-08");
			logger.info("*************开始刷新2023-09店铺运营表数据*************");
			addtpShopAnalysisReportFormsService("2023-09");
			logger.info("*************开始刷新2023-10店铺运营表数据*************");
			addtpShopAnalysisReportFormsService("2023-10");
			logger.info("*************开始刷新2023-11店铺运营表数据*************");
			addtpShopAnalysisReportFormsService("2023-11");
			logger.info("*************开始刷新2023-12店铺运营表数据*************");
			addtpShopAnalysisReportFormsService("2023-12");
			logger.info("*************完成刷新店铺运营表数据*************");
			return R.ok();
		}catch (Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
			return R.error("操作失败!");
		}
	}

	/**
	 * 手动刷新运营跟踪表数据
	 */
	@RequestMapping("/test2")
	@ResponseBody
	public R test2(HttpServletRequest request, HttpServletResponse response) {
		try {
			logger.info("*************开始统计运营跟踪表数据数据*************");
			logger.info("删除数据");
			//获取1天以前的时间日期
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.DAY_OF_MONTH, -1);
			String agoDay = sdf.format(calendar.getTime());
			//删除
			Map<String, Object> params = new HashMap<>();
			params.put("infoTime",agoDay);
			tpAmazonShopProductCountService.deleteAmazonShopProductCountYesterDay(params);
			logger.info("开始新增运营跟踪表数据数据");
			tpAmazonShopProductCountService.addTpAmazonShopOrderDaily();
			logger.info("新增运营跟踪表数据数据完成，开始修改前3天数据");
			//updateTpAmazonShopOrderDaily();
			logger.info("*************完成统计运营跟踪表数据数据*************");
			return R.ok();
		}catch (Exception e){
			logger.error(e.getMessage());
			return R.error("操作失败!");
		}

	}


	@RequestMapping("/test4")
	@ResponseBody
	public R test4(HttpServletRequest request, HttpServletResponse response) {
		return R.ok();
	}

	@RequestMapping("/test5")
	@ResponseBody
	public R test5(HttpServletRequest request, HttpServletResponse response) {
		logger.info("test5开始");
		List<TpShopAnalysisReportForms> formsList = new TpShopAnalysisReportForms()
				.setInfoTime("2023-01")
				.queryList();

		formsList.forEach(item->{
			TpShopAnalysisReportForms entity = new TpShopAnalysisReportForms();//新增参数
			if(item.getRecoveryTime()!=null){
				Date recoveryTime = item.getRecoveryTime();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
				try {
					Date oldDate = sdf.parse("2023-02-01");
					long startTimeNum = recoveryTime.getTime();
					long endTimeNum = oldDate.getTime();
					long betweenDays = (endTimeNum - startTimeNum) / (1000 * 3600 * 24);
					//开始时间和结束时间相差的天数
					int recoveryCycle = Integer.parseInt(String.valueOf(betweenDays));
					entity.setRecoveryCycle(recoveryCycle);
					entity.setId(item.getId());
					tpShopAnalysisReportFormsService.editData(entity);
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}

		});
		logger.info("test5结束");
		return R.ok();
	}

	@RequestMapping("/test3")
	@ResponseBody
	public R test3(HttpServletRequest request, HttpServletResponse response) {
		updateTpAmazonShopOrderDaily();
		return R.ok();
	}

	public void updateTpAmazonShopOrderDaily() {
		try {
			logger.info("***********定时修改运营跟踪表数据开始***********");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


			for(int i=1;i>=0;i--){
				//获取3天前时间日期
				Calendar calendar = Calendar.getInstance();
				calendar.add(Calendar.DAY_OF_MONTH, -i);
				String agoDay = sdf.format(calendar.getTime());
				logger.info("***********定时修改运营跟踪表:"+agoDay+"数据***********");
				tpAmazonShopProductCountService.updateTpAmazonShopOrderDailyByDay(agoDay);
			}



			//tpAmazonShopProductCountService.updateTpAmazonShopOrderDailyByDay("2023-11-26");

			logger.info("***********定时修改运营跟踪表前3天数据完成***********");
		}catch (Exception e){
			//e.printStackTrace();
			logger.error("定时修改运营跟踪表前3天数据出错：",e);
		}
    }


	/**
	 * 手动刷新运营日报表
	 */
	@RequestMapping("/test6")
	@ResponseBody
	public R test6(HttpServletRequest request, HttpServletResponse response) {
		try {
			logger.info("*************开始刷新刷新运营日报表*************");
			logger.info("修改数据，填入上月的增长率");
			//获取这个月时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
			Calendar calendar = Calendar.getInstance();
			String thisMonth = sdf.format(calendar.getTime());//这个月
			calendar.add(Calendar.MONTH, -1);
			String oldMonth = sdf.format(calendar.getTime());//上个月
			//tpAnalysisDailyTargetSetService.editOldMonthData("2024-06");
			logger.info("新增本月目标数据");
			tpAnalysisDailyTargetSetService.addThisMonth(thisMonth);
			//tpAnalysisDailyTargetSetService.addThisMonth("2024-11");
			logger.info("*************完成刷新刷新运营日报表*************");
			return R.ok();
		}catch (Exception e){
			logger.error(e.getMessage(),e);
			return R.error("操作失败!");
		}
	}
	/**
	 * 手动刷新运营日报表-日数据
	 */
	@RequestMapping("/test7")
	@ResponseBody
	public R test7(HttpServletRequest request, HttpServletResponse response) {
		try {
			logger.info("*************开始刷新刷新运营日报表-日数据*************");
			//获取昨天时间日期
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


			for(int i=1;i<=14;i++){
				logger.info("*************刷新第"+i+"天*************");
				Calendar calendar = Calendar.getInstance();
				calendar.add(Calendar.DAY_OF_MONTH, -i);
				String agoDay = sdf.format(calendar.getTime());//昨天
				logger.info("*************刷新:"+agoDay+" 记录*************");
				//tpAnalysisDailyTargetService.delByDay(agoDay);
				tpAnalysisDailyTargetService.addByDay(agoDay);
			}

			//Calendar calendar = Calendar.getInstance();
			//calendar.add(Calendar.DAY_OF_MONTH, -1);
			//String agoDay = sdf.format(calendar.getTime());//昨天
			/*
			String agoDay = "2023-10-16";
			logger.info("*************刷新:"+agoDay+" 记录*************");
			tpAnalysisDailyTargetService.delByDay(agoDay);


			 */
            //tpAnalysisDailyTargetService.addByDay("2023-10-25");

			logger.info("*************完成刷新刷新运营日报表-日数据*************");
			return R.ok();
		}catch (Exception e){
			logger.error(e.getMessage(),e);
			return R.error("操作失败!");
		}
	}

	/**
	 * 手动刷新运营日报表
	 */
	@RequestMapping("/test8")
	@ResponseBody
	public R test8(HttpServletRequest request, HttpServletResponse response) {
		try {
			logger.info("*************开始刷新刷新运营日报表*************");
			logger.info("修改数据，填入上月的增长率");
			//获取这个月时间
			Calendar calendar = Calendar.getInstance();
			//String thisMonth = sdf.format(calendar.getTime());//这个月
			calendar.add(Calendar.MONTH, -1);
			//tpAnalysisDailyTargetSetService.editOldMonthData(oldMonth);
			logger.info("新增本月目标数据");
			tpAnalysisDailyTargetSetService.addThisMonthByDiy("2023-08-01","2023-08-30",30);
			logger.info("*************完成刷新刷新运营日报表*************");
			return R.ok();
		}catch (Exception e){
			logger.error(e.getMessage(),e);
			return R.error("操作失败!");
		}
	}


	/**
	 * 手动刷新店铺运营表统计数据
	 */
	@RequestMapping("/test9")
	@ResponseBody
	public R test9(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("*************手动刷新店铺运营表统计数据开始*************");
			//统计上个月的运营分析表数据，总和
			tpShopAnalysisReportFormsService.addTotal("2023-10");
			logger.info("*************手动刷新店铺运营表统计数据结束*************");
			return R.ok();
		}catch (Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
			return R.error("操作失败!");
		}
	}



	/**
	 * 定时更新知识库-物流拼票
	 */
	@RequestMapping("/test10")
	@ResponseBody
	public R test10(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********每日定时更新知识库-物流拼票，开始***********");
			String timeKey = "logisticsTicket";
			//知识库分类配置信息
			EKnowTimerSet eKnowTimerSet = new EKnowTimerSet().setTimerKey(timeKey).queryFirst();
			//旧数据
			List<EKnowKnowledgeList> eKnowKnowledgeListOld = new EKnowKnowledgeList().setInfoMark(timeKey).setOrderby("A.Id").queryList();
			//物流方式信息
			List<Map<String, Object>> countLogisticsTicketGroupByName = eKnowTimerSetService.countLogisticsTicketGroupByCountry();
			//整理统计后的信息
			List<Map<String, Object>> getLogisticsTicketByCount = eKnowTimerSetService.getLogisticsTicketByCount(countLogisticsTicketGroupByName);
			//国家数据
			List<String> countryList = eKnowTimerSetService.getCountryList();
			if(getLogisticsTicketByCount!=null && getLogisticsTicketByCount.size()>0 && eKnowTimerSet!=null){

				//新增 或 修改
				if(eKnowKnowledgeListOld!=null && eKnowKnowledgeListOld.size()>0){

					for(String countryItem:countryList){
						String sectionId = timeKey+"_"+countryItem;
						List<String> informationList = new ArrayList<>();
						List<Map<String, Object>> newListByCountry = getLogisticsTicketByCount.stream().filter(item->item.get("sectionId").equals(sectionId)).collect(Collectors.toList());
						List<EKnowKnowledgeList> oldListByCountry = eKnowKnowledgeListOld.stream().filter(item->item.getSectionId().equals(sectionId)).collect(Collectors.toList());
						System.out.println("newListByCountry:\n"+newListByCountry);
						System.out.println("oldListByCountry:\n"+oldListByCountry.size());
						if(newListByCountry.size()>0){
							for(int i=0;i<newListByCountry.size();i++){
								boolean isAdd = true;
								boolean isDel = true;
								if(oldListByCountry.size()>i){
									if(newListByCountry.get(i).get("information").toString().equals(oldListByCountry.get(i).getInformation())){
										//若资料信息不变，则无需变更
										isAdd = false;
										isDel = false;
									}
								}else {
									isDel = false;
								}
								if(isDel){
									//删除
									eKnowKnowledgeListService.deleteKnowledgeListWithES(oldListByCountry.get(i).getId());
								}
								if(isAdd){//新增向量数据库
									informationList.add(newListByCountry.get(i).get("information").toString());
								}
							}
							//删除多余的信息
							if(oldListByCountry.size()>newListByCountry.size()){
								for(int i=newListByCountry.size();i<oldListByCountry.size();i++){
									//删除
									eKnowKnowledgeListService.deleteKnowledgeListWithES(oldListByCountry.get(i).getId());
								}
							}
						}else {
							if(oldListByCountry.size()>0){
								for(int i=0;i<oldListByCountry.size();i++){
									//删除
									eKnowKnowledgeListService.deleteKnowledgeListWithES(oldListByCountry.get(i).getId());
								}
							}
						}
						List<String> informationListNew = eKnowKnowledgeListService.replaceSpace(informationList);
						eKnowKnowledgeListService.addKnowledgeListByList3(eKnowTimerSet.getBaseId(),eKnowTimerSet.getTypeId(),informationListNew,sectionId,timeKey,"admin");
					}

				}else {//从未添加过
					//addTimerListByNew(timeKey,getLogisticsTicketByCount,eKnowTimerSet,countLogisticsTicketGroupByName);for(String countryItem:countryList){
					for(String countryItem:countryList){
						addTimerListByNameAndNew(timeKey,getLogisticsTicketByCount,eKnowTimerSet,countryItem);
					}
				}
			}else {
				if(eKnowKnowledgeListOld!=null && eKnowKnowledgeListOld.size()>0){
					//删除
					for(EKnowKnowledgeList item:eKnowKnowledgeListOld){
						eKnowKnowledgeListService.deleteKnowledgeListWithES(item.getId());
					}
				}
			}
			logger.info("***********每日定时更新知识库-物流拼票，完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("定时更新知识库-物流拼票出错：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}


	/**
	 * 定时更新知识库、向量数据库-物流拼票
	 */
	@RequestMapping("/test11")
	@ResponseBody
	public R test11(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********每日定时更新向量数据库-物流拼票，开始***********");
			String timeKey = "logisticsTicket";
			List<EKnowKnowledgeList> oldList = new EKnowKnowledgeList().setInfoMark(timeKey).queryList();
			//物流方式信息
			List<Map<String, Object>> countLogisticsTicketGroupByName = eKnowTimerSetService.countLogisticsTicketGroupByCountry();
			//整理统计后的信息
			List<Map<String, Object>> newList = eKnowTimerSetService.getLogisticsTicketByCount(countLogisticsTicketGroupByName);
			//处理
			addTimerListByOld(timeKey,oldList,newList);
			logger.info("***********每日定时更新向量数据库-物流拼票，完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("定时更新知识库-物流拼票出错：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}

	//新增知识库信息 根据物流方式
	public void addTimerListByNameAndNew(String timeKey,List<Map<String, Object>> getLogisticsTicketByCount,
										 EKnowTimerSet eKnowTimerSet,String nameLogsticsWay) throws Exception{
		List<Map<String, Object>> newList = getLogisticsTicketByCount.stream().filter(item->item.get("sectionId").equals(timeKey+"_"+nameLogsticsWay)).collect(Collectors.toList());
		List<String> informationList = new ArrayList<>();
		for(Map<String, Object> item:newList){
			informationList.add(item.get("information").toString());
			eKnowKnowledgeListService.addKnowledgeListByList3(eKnowTimerSet.getBaseId(),eKnowTimerSet.getTypeId(),informationList,timeKey+"_"+nameLogsticsWay,timeKey,"admin");
		}
	}


	//根据知识库信息，删除后新增
	public void addTimerListByOld(String timeKey,List<EKnowKnowledgeList> oldList,List<Map<String, Object>> newList) throws Exception{
		if(oldList!=null && oldList.size()>0){
			//删除
			for(EKnowKnowledgeList item:oldList){
				eKnowKnowledgeListService.deleteKnowledgeListWithES(item.getId());
			}
		}
		//新增
		EKnowTimerSet eKnowTimerSet = new EKnowTimerSet().setTimerKey(timeKey).queryFirst();
		if(eKnowTimerSet!=null && newList!=null && newList.size()>0 ){
			for(Map<String, Object> markItem:newList){
				List<String> informationList = new ArrayList<>();
				String sectionId = markItem.get("sectionId").toString();
				informationList.add(markItem.get("information").toString());
				eKnowKnowledgeListService.addKnowledgeListByList3(eKnowTimerSet.getBaseId(),eKnowTimerSet.getTypeId(),informationList,sectionId,timeKey,"admin");
			}
		}
	}


	/**
	 * 定时更新统计财务核账表
	 */
	@RequestMapping("/test12")
	@ResponseBody
	public R test12(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********定时统计财务核账表开始***********");
			//获取当前时间日期
			//reFinanceExamineService.countReFinanceExamine(nowDate,"12:00:00");
			reFinanceExamineService.countReFinanceExamineByHistory("2024-04-29","23:59:59");
			logger.info("***********1***********");
			reFinanceExamineService.countReFinanceExamineByHistory("2024-04-30","23:59:59");
			logger.info("***********2***********");
			reFinanceExamineService.countReFinanceExamineByHistory("2024-05-01","23:59:59");
			logger.info("***********3***********");
			reFinanceExamineService.countReFinanceExamineByHistory("2024-05-02","23:59:59");
			logger.info("***********4***********");
			reFinanceExamineService.countReFinanceExamineByHistory("2024-05-03","23:59:59");
			logger.info("***********5***********");
			reFinanceExamineService.countReFinanceExamineByHistory("2024-05-04","23:59:59");
			logger.info("***********6***********");
			reFinanceExamineService.countReFinanceExamineByHistory("2024-05-05","23:59:59");
			logger.info("***********7***********");
			//reFinanceExamineService.countReFinanceExamineByHistory("2024-05-06","23:59:59");
			logger.info("***********定时统计财务核账表完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("定时统计财务核账表出错：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}



	/**
	 * 统计部门业务收支报告
	 */
	@RequestMapping("/test13")
	@ResponseBody
	public R test13(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********定时统计部门业务收支报告--开始***********");
			/*
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
			//获取当前时间日期
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.MONTH, -1);//上个月
			String oldMonth = sdf.format(calendar.getTime());

			for(int i=1;i<=12;i++){
				String aaa = "2023-"+(i<10?"0"+i:i);
				logger.info("***********定时统计部门业务收支报告："+aaa+"***********");
				reDeptRevenueExpenditureService.countReDeptRevenueExpenditure(aaa);
			}*/
			String bbb = "2024-04";
			logger.info("***********定时统计部门业务收支报告："+bbb+"***********");
			reDeptRevenueExpenditureService.countReDeptRevenueExpenditure(bbb);
			//bbb = "2024-02";
			//logger.info("***********定时统计部门业务收支报告："+bbb+"***********");
			//reDeptRevenueExpenditureService.countReDeptRevenueExpenditure(bbb);
			logger.info("***********定时统计部门业务收支报告--完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("定时统计财务核账表出错：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}

	/**
	 * 定时更新统计财务核账表

	@RequestMapping("/test14")
	@ResponseBody
	public R test14(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********精品库新增开始***********");
			//code商品编码；name商品名称；codeMerge合并商品编码；boutiqueIsEffect精品是否生效(0未生效，1已生效)
			Map<String, Object> params = new HashMap<>();
			params.put("code","0001");
			params.put("name","测试");
			params.put("codeMerge","0001");
			params.put("boutiqueIsEffect",0);
			TpBoutique tpBoutique = JSON.parseObject(JSON.toJSONString(params), TpBoutique.class);
			tpBoutiqueService.add(tpBoutique);
			logger.info("***********精品库新增完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}*/
	/**
	 * 定时更新店铺排名信息
	 */
	@RequestMapping("/test15")
	@ResponseBody
	public R test15(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			tcoRankShopByAmountRmbService.addTcoRankShopByAmountRmb();
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}


	/**
	 * 定时更新统计财务核账表
	 */
	@RequestMapping("/test14")
	@ResponseBody
	public R test14(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********精品库新增开始***********");
			//code商品编码；name商品名称；codeMerge合并商品编码；boutiqueIsEffect精品是否生效(0未生效，1已生效)
			Map<String, Object> params = new HashMap<>();
			params.put("code","0001");
			params.put("name","测试");
			params.put("codeMerge","0001");
			params.put("boutiqueIsEffect",0);
			TpBoutique tpBoutique = JSON.parseObject(JSON.toJSONString(params), TpBoutique.class);
			tpBoutiqueService.add(tpBoutique);
			logger.info("***********精品库新增完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}



	/**
	 * 通过高德API更新城市信息数据
	 */
	@RequestMapping("/updateCity")
	@ResponseBody
	public R updateCity(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********更新城市信息开始***********");
			String url = "https://restapi.amap.com/v3/config/district?key=6b1ba32b899e2f8f7fd592f6f79420f2&subdistrict=3";
			URL apiUrl = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
			connection.setRequestMethod("GET");
			int responseCode = connection.getResponseCode();
			if (responseCode == HttpURLConnection.HTTP_OK) {
				BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				String inputLine;
				StringBuffer response1 = new StringBuffer();

				while ((inputLine = reader.readLine()) != null) {
					response1.append(inputLine);
				}
				reader.close();
				System.out.println("返回参数: "+response1.toString());
				JSONObject jsonObject = JSONObject.parseObject(response1.toString());
				//国家信息
                JSONArray jsonArray1 = JSONArray.parseArray(jsonObject.get("districts").toString());
                //第一个是中国
                JSONObject jsonObject2 =  jsonArray1.getJSONObject(0);
                //省份信息
                JSONArray jsonArray2 = JSONArray.parseArray(jsonObject2.get("districts").toString());
                //删除
				tbBaseInfoAreaService.delAll();
                for(int i=0;i<jsonArray2.size();i++){
                    JSONObject jsonObjectSf =  jsonArray2.getJSONObject(i);
                    Map<String, Object> params1 = new HashMap<>();
                    params1.put("code",jsonObjectSf.get("adcode").toString());//编码
                    params1.put("name",jsonObjectSf.get("name").toString());//名称
                    params1.put("level",1);
                    params1.put("pid",0);
                    params1.put("status",1);
                    TbBaseInfoArea tbBaseInfoCity1 = tbBaseInfoAreaService.add(params1);
                    //城市信息
                    JSONArray jsonArray3 = JSONArray.parseArray(jsonObjectSf.get("districts").toString());
                    for(int j=0;j<jsonArray3.size();j++) {
						String name = jsonObjectSf.get("name").toString();
                        JSONObject jsonObjectS = jsonArray3.getJSONObject(j);
                        Map<String, Object> params2 = new HashMap<>();
                        params2.put("code",jsonObjectS.get("adcode").toString());//编码
                        params2.put("name",jsonObjectS.get("name").toString());//名称
                        params2.put("level",2);
                        params2.put("pid",tbBaseInfoCity1.getId());
						params2.put("higherLevelPath",name);
                        params2.put("status",1);
						TbBaseInfoArea tbBaseInfoCity2 = tbBaseInfoAreaService.add(params2);
                        //区县信息
                        JSONArray jsonArray4 = JSONArray.parseArray(jsonObjectS.get("districts").toString());
                        for(int z=0;z<jsonArray4.size();z++) {
							name = jsonObjectSf.get("name").toString() + ","+ jsonObjectS.get("name").toString();
                            JSONObject jsonObjectQX = jsonArray4.getJSONObject(z);
                            Map<String, Object> params3 = new HashMap<>();
                            params3.put("code",jsonObjectQX.get("adcode").toString());//编码
                            params3.put("name",jsonObjectQX.get("name").toString());//名称
                            params3.put("level",3);
                            params3.put("pid",tbBaseInfoCity2.getId());
                            params3.put("status",1);
							params3.put("higherLevelPath",name);
							//name = jsonObjectSf.get("name").toString() + ","+ jsonObjectS.get("name").toString() + ","+ jsonObjectQX.get("name").toString();
							tbBaseInfoAreaService.add(params3);
                        }
                    }
                }


            } else {
				System.out.println("GET request failed. Response code: " + responseCode);
			}
			logger.info("***********更新城市信息完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}


	/**
	 * 同步刷新旧员工的档案
	 */
	@RequestMapping("/updateUserDanAn")
	@ResponseBody
	public R updateUserDanAn(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********同步刷新员工档案开始***********");
			List<TsUserInfo> userList = new TsUserInfo()
					.where("( SELECT COUNT ( 1 ) AS num FROM THR_UserArchives B WHERE B.UserId = A.UserId ) = 0 ")
					//.setStatus(1)//在职
					.queryList();
			Date theDate = new Date();
			if(userList!=null && userList.size()>0){
				for(TsUserInfo item : userList){
					Map<String, Object> paramsByUserArchives = new HashMap<>();
					int num = 0;
					//设置档案编码（格式：YGDA年月日三位序号）
					if(redisUtil.get("thrUserArchivesBid")!= null && !"".equals(redisUtil.get("ThrUserArchivesBid"))){
						num = Integer.parseInt(redisUtil.get("thrUserArchivesBid"))+1;
					}
					redisUtil.set("thrUserArchivesBid",num+"");//加一更新
					LocalDateTime midnight = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
					long seconds = ChronoUnit.SECONDS.between(LocalDateTime.now(), midnight);
					redisUtil.setEx("thrUserArchivesBid",num+"",seconds, TimeUnit.SECONDS);//设置过期时间
					//设置档案编码（格式：YGDA年月日三位序号）
					String archivesBid = "YGDA"+ DateUtil.getYYYYMMDD(theDate)+String.format("%0"+5+"d", num);
					//入参
					logger.info("***********同步刷新员工档案开始:"+item.getUserId()+"***********");
					paramsByUserArchives.put("archivesBid",archivesBid);//档案编码（格式：YGDA年月日三位序号）
					paramsByUserArchives.put("userId",item.getUserId());//用户工号
					paramsByUserArchives.put("userName",item.getUserName());//用户名字
					//if(item.getUserSex()!=null)paramsByUserArchives.put("userSex",item.getUserSex()!=null&&item.getUserSex().equals("女")?0:1);//性别
					//if(item.getUserBirthday()!=null)paramsByUserArchives.put("birthday",item.getUserBirthday()!=null?DateUtil.getYYYY_MM_DD(item.getUserBirthday()):null);//生日
					//paramsByUserArchives.put("education",entity.getEducation());//学历
					//paramsByUserArchives.put("graduationDate",entity.getGraduationDate());//毕业日期(YYYY-MM-DD)
					//if(item.getUserSchooled()!=null)paramsByUserArchives.put("graduationSchool",item.getUserSchooled()!=null?item.getUserSchooled():null);//毕业学校
					//paramsByUserArchives.put("major",entity.getMajor());//主修专业
					//if(item.getUserPhone1()!=null)paramsByUserArchives.put("telephone",item.getUserPhone1()!=null?item.getUserPhone1():null);//联系电话
					//if(item.getUserAddress()!=null)paramsByUserArchives.put("address",item.getUserAddress()!=null?item.getUserAddress():null);//居住地址
					//paramsByUserArchives.put("workCity",entity.getWorkCity());//工作城市
					if(item.getRoleId()!=null)paramsByUserArchives.put("roleId",item.getRoleId()!=null?item.getRoleId():null);//岗位
					//if(item.getUserType()!=null)paramsByUserArchives.put("roleIdAttribute",item.getUserType()!=null&&item.getUserType().equals("运营")?1:0);//岗位属性
//					if(item.getOrgid()!=null)paramsByUserArchives.put("deptId",item.getDeptId()!=null?item.getDeptId():null);//部门
					if(item.getUserLeader()!=null)paramsByUserArchives.put("headUserId",item.getUserLeader()!=null?item.getUserLeader():null);//上级用户工号
					if(item.getCompanyVid()!=null)paramsByUserArchives.put("belongCompany",item.getCompanyVid()!=null?item.getCompanyVid():null);//所属公司
					//paramsByUserArchives.put("graduationCertificate",entity.getGraduationCertificate());//毕业证书附件路径
					//paramsByUserArchives.put("educationCertificate",entity.getEducationCertificate());//学历证书附件路径
					//paramsByUserArchives.put("laborContract",entity.getLaborContract());//劳动合同附件路径
					//paramsByUserArchives.put("otherFile",entity.getOtherFile());//其他附件路径
					//if(item.getVBzXx()!=null)paramsByUserArchives.put("remark",item.getVBzXx());//备注
					if(item.getStatus()!=null)paramsByUserArchives.put("userState",item.getStatus()==1?2:3);//员工状态（0实习、1试用、2正式、3离职）
					//if(item.getDRzSj()!=null)paramsByUserArchives.put("entryDate",item.getDRzSj()!=null?DateUtil.getYYYY_MM_DD(item.getDRzSj()):null);//入职时间
					//if(item.getDLzSj()!=null)paramsByUserArchives.put("departDate",item.getDLzSj()!=null?DateUtil.getYYYY_MM_DD(item.getDLzSj()):null);//离职时间
					thrUserArchivesService.add(paramsByUserArchives);
				}
			}



			logger.info("***********同步刷新员工档案完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}



	/**
	 * 定时更新店铺排名信息
	 */
	@RequestMapping("/test16")
	@ResponseBody
	public R test16(HttpServletRequest request, HttpServletResponse response,String time
	) {
		try {
			logger.info("***********开始更新店铺排名信息:"+time+"***********");
			tcoRankShopByAmountRmbService.addTcoRankShopByAmountRmbByTime(time);
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}





	/**
	 * 定时更新店铺排名信息
	 */
	@RequestMapping("/test17")
	@ResponseBody
	public R test17(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			apiHttpUtils.sendHttpPost(null, "http://localhost:8090/api/outer/dingDingApi/getDingDingUserIdByPhone");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}




	/**
	 * 刷新运营公司管理表的用户信息
	 */
	@RequestMapping("/test18")
	@ResponseBody
	public R test18(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			List<ThrOperateCompanyApply> companyList = new ThrOperateCompanyApply().queryList();
			List<TsUserChange> changeList = new TsUserChange().setOrderby("A.Id DESC").queryList();
			if(companyList!=null && companyList.size()>0){
				for(ThrOperateCompanyApply comItem:companyList){
					if(comItem.getCuser()!=null && !"".equals(comItem.getCuser())){
						List<TsUserChange> changeListByUserId = changeList.stream().filter(item->item.getUserId().equals(comItem.getCuser())).collect(Collectors.toList());
						if(changeListByUserId.size()>0){
							TsUserChange tsUserChange = changeListByUserId.get(0);
							ThrOperateCompanyApply thrOperateCompanyApply = new ThrOperateCompanyApply();
							thrOperateCompanyApply.setId(comItem.getId());
							thrOperateCompanyApply.setOperatorChangeId(tsUserChange.getId());
							thrOperateCompanyApplyMapper.update(thrOperateCompanyApply);
						}
					}
				}
			}
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}



	/**
	 * 刷新用户钉钉id
	 */
	@RequestMapping("/test19")
	@ResponseBody
	public R test19(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			String sentUrl = URLAPI2_0;
			sentUrl = sentUrl + "/api/outer/dingDingApi/getDingDingUserIdByPhone";
			List<ThrUserArchives> thrUserArchivesList = new ThrUserArchives()
					.where("A.Telephone IS NOT NULL AND A.DingDingId IS NULL")
					.queryList();
			for(ThrUserArchives thrUserArchives : thrUserArchivesList){
				logger.info("***********开始刷新"+thrUserArchives.getUserId()+"***********");
				Map<String, Object> sendParams = new HashMap<>();
				sendParams.put("telephone",thrUserArchives.getTelephone());//联系电话
				sendParams.put("userId",thrUserArchives.getUserId());//用户id
			}

			List<Map<String,Object>> companyList = new TsUserInfo()
					.addLeftJoin("TS_OrganizationInfo E ON E.Id = A.Orgid")
					.addLeftJoin("TS_OrganizationInfo E1 ON E1.Id = E.Pid")
					.addLeftJoin("TS_UserInfo E2 on E2.UserId = E1.HeadUserId")
					.addLeftJoin("TS_UserInfo F on F.UserId = E.HeadUserId")
					.addField("E2.UserId AS e2UserId")
					.addField("F.UserId AS fUserId")
					.addField("E.HeadUserId AS eHeadUserId")
					.queryMap();
			for(Map<String,Object> item:companyList){
				TsUserInfo tsUserInfo= new TsUserInfo();
				logger.info("***********开始:"+item.get("userId")+"***********");
				if(item.get("eHeadUserId")!=null){
					tsUserInfo.setId(Long.parseLong(item.get("id").toString()));
					String userId = item.get("userId").toString();
					if(item.get("eHeadUserId").equals(userId)  ){
						if(item.get("e2UserId")!=null){
							tsUserInfo.setUserLeader(item.get("e2UserId").toString());
							tsUserInfoMapper.update(tsUserInfo);
						}
					}else {
						if(item.get("fUserId")!=null){
							tsUserInfo.setUserLeader(item.get("fUserId").toString());
							tsUserInfoMapper.update(tsUserInfo);
						}

					}
				}

			}

			/*
			.addField("(CASE WHEN A.UserId = E.HeadUserId THEN E2.UserId ELSE F.UserId END) userIdUp") // 若用户是机构负责人，则用户上级为机构上级的部门负责人
			.addField("(CASE WHEN A.UserId = E.HeadUserId THEN E2.UserName ELSE F.UserName END) userNameUp");
			 */

			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}

	/**
	 * 刷新员工职级管理
	 */
	@RequestMapping("/test20")
	@ResponseBody
	public R test20(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			List<Map<String,Object>> infoList = new TbUserJobLevelManage().queryMap();
			for(Map<String,Object> item:infoList){
				logger.info("***********开始:"+item.get("userId")+"***********");
				R res = tbUserJobLevelManageService.save(item, MenuId.TB_UserJobLevelManage,false);
				logger.info("***********开始:"+res.getMsg()+"***********");
			}
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}



	/**
	 * 手动刷新员工工资条
	 */
	@RequestMapping("/test21")
	@ResponseBody
	public R test21(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");

			/*
			List<TbUserMonthPerformance> tbUserMonthPerformanceList = new TbUserMonthPerformance()
					.setPointMonth("2025-01")
					.queryList();

			 */

			/*
			for(TbUserMonthPerformance tbUserMonthPerformance : tbUserMonthPerformanceList){
				logger.info("***********绩效开始:"+tbUserMonthPerformance.getUserId()+"***********");
				Map<String,Object> entity = new TbUserJobLevelManage()

						.addLeftJoin("TB_JobLevel J ON J.Id = A.RoleLevelId")//岗位职级表
						.addField("J.Rank AS rank")//岗位职级
						.addField("J.Category AS category")//岗位类别
						.addField("J.Categories AS categories")//职级大类
						.addField("J.Type AS type")//岗位工种
						.addField("J.JobPromotion AS jobBonus")//岗位提奖/月

						.addField("J.PerbasedSalary AS perbasedSalary")//绩效薪资/月
						.addField("J.QuarterlyBonus AS quarterlyBonus")//季度提奖/月
						.addField("J.SalaryStandard AS salaryStandard")//发薪标准/月
						.addField("J.BasicSalary AS basicSalary")//基本底薪/月
						.addField("J.PositionSalary AS positionSalary")//岗位薪资/月
						.addField("J.TransSubsidy AS transSubsidy")//交通补贴/月
						.addField("J.CateringSubsidy AS cateringSubsidy")//餐饮补贴/月
						.addField("J.FixsalaryStandard AS fixsalaryStandard")//定薪标准


						.addLeftJoin("TB_SocialSecurity S ON S.Id = A.SocialSecurityId")//社保管理表
						.addField("S.SoseBase AS soseBase")//社保基数
						.addField("S.PiUnitMonth AS piUnitMonth")//养老保险（单位）
						.addField("S.PiIndividualMonth AS piIndividualMonth")//养老保险（个人）
						.addField("S.UiUnitMonth AS uiUnitMonth")//失业保险（单位）
						.addField("S.UiIndividualMonth AS uiIndividualMonth")//失业保险（个人）
						.addField("S.WiiUnitMonth AS wiiUnitMonth")//工伤保险（单位）

						.addLeftJoin("TB_MedicalInsurance M ON M.Id = A.MedicalInsuranceId")//医保管理表
						.addField("M.MiBase AS miBase")//医保基数
						.addField("M.MiUnitMoonth AS miUnitMoonth")//医疗保险（单位）
						.addField("M.MiIndividualMonth AS miIndividualMonth")//医疗保险（个人）
						.addField("M.MiUnitMonth AS miUnitMonth")//生育保险（单位）

						.addLeftJoin("TB_ProvidentFund P ON P.Id = A.AccumulationFundId")//公积金管理表
						.addField("P.HousingPfBase AS housingPfBase")//公积金基数
						.addField("P.PfUnitMonth AS pfUnitMonth")//公积金（单位）
						.addField("P.PfIndividualMonth AS pfIndividualMonth")//公积金（个人）

						.addLeftJoin("TB_Attendance AD ON AD.Id = A.AttendanceId")//考勤管理表
						.addField("AD.Type AS attendanceType")//考勤类型
						.addField("AD.MonthlyAsDay AS monthlyAsDay")//月考勤标准（天）
						.addField("AD.DailyAsHour AS dailyAsHour")//日考勤标准（小时）/月
						.addField("AD.PaidPersonalLeave AS paidPersonalLeave")//带薪事假-其他（小时）



						.setId(tbUserMonthPerformance.getUserJobLevelManageId())
						.queryFirstMap();
				logger.info("***********开始entity:"+entity+"***********");
				TbUserMonthPerformance tbUserMonthPerformanceByNew = JSON.parseObject(JSON.toJSONString(entity), TbUserMonthPerformance.class);

				tbUserMonthPerformanceByNew.setId(tbUserMonthPerformance.getId());

				if(tbUserMonthPerformance.getUserId().equals("01046")){
					tbUserMonthPerformanceByNew.setPiUnitMonth(BigDecimal.ZERO);//养老保险（单位）、
					tbUserMonthPerformanceByNew.setPiIndividualMonth(BigDecimal.ZERO);// 养老保险（个人）、
					tbUserMonthPerformanceByNew.setUiUnitMonth(BigDecimal.ZERO);// 失业保险（单位）、
					tbUserMonthPerformanceByNew.setUiIndividualMonth(BigDecimal.ZERO);// 失业保险（个人）、
					tbUserMonthPerformanceByNew.setWiiUnitMonth(BigDecimal.ZERO);// 工伤保险（单位）、
					tbUserMonthPerformanceByNew.setPfUnitMonth(BigDecimal.ZERO);// 公积金（单位）、
					tbUserMonthPerformanceByNew.setPfIndividualMonth(BigDecimal.ZERO);// 公积金（个人）
				}


				tbUserMonthPerformanceMapper.update(tbUserMonthPerformanceByNew);
			}

			 */


			List<TbUserPaySlip> tbUserPaySlip = new TbUserPaySlip()

					.setPointMonth("2025-02")
					.queryList();


			for(TbUserPaySlip item:tbUserPaySlip){
				logger.info("***********开始:"+item.getUserId()+"***********");
				R res = tbUserPaySlipService.importUserTaxByUpdate(item.getId());
				logger.info("***********开始:"+res.getMsg()+"***********");
			}

			logger.info("***********刷新申请表信息***********");
			tbUserPayApplyService.updateTotalCount();
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}


	@RequestMapping("/test200")
	@ResponseBody
	public R test200(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			TcwAccountDetailedForCompany tcwAccountDetailedForCompany = new TcwAccountDetailedForCompany()
					.setId(1227439L).queryFirst();
			tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
					"GS0889","问前集团",
					"HZZH0002", "AMAZON","经营费用→手续费",
					tcwAccountDetailedForCompany.getFje().negate(),new Date(),new Date(),
					tcwAccountDetailedForCompany.getVbz(),
					tcwAccountDetailedForCompany.getMbid(),new Date());
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}





	/**
	 * 手动刷新员工个税的运营机构信息
	 */
	@RequestMapping("/test22")
	@ResponseBody
	public R test22(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			List<TbUserPaySlip> tbUserPaySlip = new TbUserPaySlip().queryList();
			for(TbUserPaySlip item:tbUserPaySlip){
				logger.info("***********开始:"+item.getUserId()+"***********");
				TbUserPersonalTaxCount tbUserPersonalTaxCount = new TbUserPersonalTaxCount().setPaySlipId(item.getId()).queryFirst();
				if(tbUserPersonalTaxCount!=null){
					tbUserPersonalTaxCount.setOrgId(item.getOrgId());
					tbUserPersonalTaxCountMapper.update(tbUserPersonalTaxCount);
				}
			}
			logger.info("***********刷新申请表信息***********");
			//tbUserPayApplyService.updateTotalCount();
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}



	/**
	 * 手动刷新员工个税的运营机构信息
	 */
	@RequestMapping("/test23")
	@ResponseBody
	public R test23(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			List<TbUserPersonalTaxCount> list = new TbUserPersonalTaxCount().setCountMonth("2024-05").queryList();
			for(TbUserPersonalTaxCount item:list){
				logger.info("***********开始:"+item.getUserId()+"***********");
				TbUserPersonalTaxCount tbUserPersonalTaxCount = new TbUserPersonalTaxCount().setCountMonth("2024-04").setUserId(item.getUserId()).queryFirst();
				if(tbUserPersonalTaxCount!=null){
					tbUserPersonalTaxCount.setOrgId(item.getOrgId());
					tbUserPersonalTaxCountMapper.update(tbUserPersonalTaxCount);
				}
			}
			logger.info("***********刷新申请表信息***********");
			//tbUserPayApplyService.updateTotalCount();
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}



	/**
	 * 手动刷新运营公司预付款管理
	 */
	@RequestMapping("/test24")
	@ResponseBody
	public R test24(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			//tcwOperateCompanyPrepaymentService.add("2024-07","GS0637");
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}


	/**
	 * 手动刷新收取资金占用费
	 */
	@RequestMapping("/test25")
	@ResponseBody
	public R test25(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			tcwAccountDetailedForCompanyService.fundOccupyCost();
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}



	/**
	 * 手动刷新收取占库费
	 */
	@RequestMapping("/test26")
	@ResponseBody
	public R test26(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			tcwAccountDetailedForCompanyService.occupyInventoryCost();
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}



	/**
	 * 手动刷新
	 */
	@RequestMapping("/test27")
	@ResponseBody
	public R test27(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			//
			List<TcwAccountDetailedForCompany> list = new TcwAccountDetailedForCompany()
					.where("A.Id IN(1330862,1330863,1330864,1330865,1330866,1330867,1330868,1330869)")
					//.where("A.DJySj BETWEEN '2024-08-22 08:00:00' AND '2024-08-22 23:59:59'")
					.queryList();
			for(TcwAccountDetailedForCompany item:list){
				System.out.println(item.getVgsbm()+":"+ item.getFje() );
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
						item.getVgsbm(),item.getVgsjc(),
						item.getVgsbmp(),item.getVgsjcp(),
						item.getVjylx(), BigDecimal.ZERO.subtract(item.getFje()),item.getDjysj(), item.getDshsj(),
						item.getVbz(),
						item.getMbid(),item.getWriteTime() );

			}
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}





	/**
	 * 手动刷新 - bi分类模块业务流水分析汇总表
	 */
	@RequestMapping("/test28")
	@ResponseBody
	public R test28(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			//
			biClassifyModuleService.updateByDay();
			biClassifyModuleService.updateByMonth("2023-08");
			biClassifyModuleService.updateByMonth("2023-09");
			biClassifyModuleService.updateByMonth("2023-10");
			biClassifyModuleService.updateByMonth("2023-11");
			biClassifyModuleService.updateByMonth("2023-12");
			biClassifyModuleService.updateByMonth("2024-01");
			biClassifyModuleService.updateByMonth("2024-02");
			biClassifyModuleService.updateByMonth("2024-03");
			biClassifyModuleService.updateByMonth("2024-04");
			biClassifyModuleService.updateByMonth("2024-05");
			biClassifyModuleService.updateByMonth("2024-06");
			biClassifyModuleService.updateByMonth("2024-07");
			biClassifyModuleService.updateByMonth("2024-08");
			biClassifyModuleService.updateByMonth("2024-09");



			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}


	/**
	 * 手动刷新 - bi流水分析统计汇总表
	 */
	@RequestMapping("/test29")
	@ResponseBody
	public R test29(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			//
			biFlowAnalysisService.updateByDay();
			biFlowAnalysisService.updateByMonth("2023-08");
			biFlowAnalysisService.updateByMonth("2023-09");
			biFlowAnalysisService.updateByMonth("2023-10");
			biFlowAnalysisService.updateByMonth("2023-11");
			biFlowAnalysisService.updateByMonth("2023-12");
			biFlowAnalysisService.updateByMonth("2024-01");
			biFlowAnalysisService.updateByMonth("2024-02");
			biFlowAnalysisService.updateByMonth("2024-03");
			biFlowAnalysisService.updateByMonth("2024-04");
			biFlowAnalysisService.updateByMonth("2024-05");
			biFlowAnalysisService.updateByMonth("2024-06");
			biFlowAnalysisService.updateByMonth("2024-07");
			biFlowAnalysisService.updateByMonth("2024-08");
			biFlowAnalysisService.updateByMonth("2024-09");
			biFlowAnalysisService.updateByYear("2023");
			biFlowAnalysisService.updateByYear("2024");

			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}

	@RequestMapping("/test30")
	@ResponseBody
	public R test30(HttpServletRequest request, HttpServletResponse response
	) {

		TbUserPaySlip tbUserPaySlipByOld = new TbUserPaySlip().setId(521L).queryFirst();
		if(tbUserPaySlipByOld!=null){
			Map<String,Object> tbUserMonthPerformance = tbUserPaySlipService.getCountInfo(tbUserPaySlipByOld.getMonthPerformanceId());
			//工资条计算
			tbUserPaySlipByOld = tbUserPaySlipService.countPaySlip(tbUserPaySlipByOld,tbUserMonthPerformance);
			tbUserPaySlipMapper.update(tbUserPaySlipByOld);
		}

		return R.ok();
	}


	@RequestMapping("/test31")
	@ResponseBody
	public R test31(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			List<TcwCapitalBusinessCost> list = new TcwCapitalBusinessCost()
					.addLeftJoin("YS_ProcInst B ON A.Bid = B.Bid")
					.where("B.Bid IS NULL")
					.queryList();
			for(TcwCapitalBusinessCost item:list){
				logger.info("***********"+item.getBid()+"***********");
				YsMenu ysMenu = new YsMenu().setId(10306L).queryFirst();
				if (ysMenu.getFlowModelId().longValue() != 0L) {
					YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
					String codeModel = yspModel.getCode();
					String createUserId = "00180";//ShiroUtils.getUserId();
					yspTaskService.init(codeModel, item.getBid(), createUserId);
				}
				yspTaskService.flowPass(item.getBid(),"00180");
			}
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}




	@RequestMapping("/test32")
	@ResponseBody
	public R test32(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			TcgPurchaseByOrder tcgPurchaseByOrder = new TcgPurchaseByOrder().setBid("CGDD-241210-1003").queryFirst();
			tcgPurchaseByOrderService.countSubRealityPrice(tcgPurchaseByOrder);
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}


	@RequestMapping("/test33")
	@ResponseBody
	public R test33(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			//R res = tcwWanliDrawingService.flowFinish("WFTK-250226-1001");
			tcwWanliDrawingService.paySuccess(19L);
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}




	@RequestMapping("/test34")
	@ResponseBody
	public R test34(HttpServletRequest request, HttpServletResponse response,String countMonth
	) {
		try {
			logger.info("***********开始***********");
			//String countMonth = "2025-02";
			tcoBusinessDataStatService.count(countMonth);
			tcoBusinessDataStatService.countYearAdded(countMonth);
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}





	@RequestMapping("/test35")
	@ResponseBody
	public R test35(HttpServletRequest request, HttpServletResponse response,String countMonth
	) {
		try {
			logger.info("***********开始***********");
			List<TpProductActive> tpProductActiveList = new TpProductActive()
					.setVgsBm("GS0006")
					.where("A.Code LIKE '%YP250327%'")
					.queryList();


			List<TpProductBasis> tpProductBasiList = new TpProductBasis()
					.setVgsBm("GS0006")
					.where("A.Code LIKE '%YP250327%'")
					.queryList();



			if(tpProductActiveList!=null && tpProductActiveList.size()>0){
				for(TpProductActive tpProductActive:tpProductActiveList){
					logger.info("***********开始ListIng:"+tpProductActive.getCode()+"***********");
					TpProductActive tpProductActiveByOld = new TpProductActive().setCode(tpProductActive.getCodeMerge()).queryFirst();
					if(tpProductActiveByOld!=null && tpProductActiveByOld.getId()!=null){
						tpProductActive.setCodeHs(tpProductActiveByOld.getCodeHs());
						tpProductActive.setSizeLength(tpProductActiveByOld.getSizeLength());
						tpProductActive.setSizeWidth(tpProductActiveByOld.getSizeWidth());
						tpProductActive.setSizeHeight(tpProductActiveByOld.getSizeHeight());
						tpProductActive.setSizeWeight(tpProductActiveByOld.getSizeWeight());
						tpProductActive.setCommodityPlId(tpProductActiveByOld.getCommodityPlId());
						tpProductActive.setNameId(tpProductActiveByOld.getNameId());

						tpProductActiveMapper.update(tpProductActive);
						List<TpProductMaterial> tpProductMaterialList = new TpProductMaterial()
								.setProductCode(tpProductActive.getCode())
								.setType(TpProductMaterialEnum.Type.TP_ProductActive.value)
								.queryList();
						if(tpProductMaterialList==null || tpProductMaterialList.size()<=0){

							List<TpProductMaterial> tpProductMaterialListByOld = new TpProductMaterial()
									.setProductCode(tpProductActiveByOld.getCode())
									.setType(TpProductMaterialEnum.Type.TP_ProductActive.value)
									.queryList();
							if(tpProductMaterialListByOld!=null && tpProductMaterialListByOld.size()>0){
								for(TpProductMaterial tpProductMaterialByOld:tpProductMaterialListByOld){
									tpProductMaterialByOld.setProductCode(tpProductActive.getCode());
									tpProductMaterialMapper.insert(tpProductMaterialByOld);
								}
							}
						}
					}
				}

			}



			if(tpProductBasiList!=null && tpProductBasiList.size()>0){
				for(TpProductBasis tpProductBasis:tpProductBasiList){
					logger.info("***********开始商品:"+tpProductBasis.getCode()+"***********");
					TpProductBasis tpProductBasisByOld = new TpProductBasis().setCode(tpProductBasis.getCodeMerge()).queryFirst();
					if(tpProductBasisByOld!=null && tpProductBasisByOld.getId()!=null){
						tpProductBasis.setCodeHs(tpProductBasisByOld.getCodeHs());
						tpProductBasis.setSizeLength(tpProductBasisByOld.getSizeLength());
						tpProductBasis.setSizeWidth(tpProductBasisByOld.getSizeWidth());
						tpProductBasis.setSizeHeight(tpProductBasisByOld.getSizeHeight());
						tpProductBasis.setSizeWeight(tpProductBasisByOld.getSizeWeight());
						tpProductBasis.setCommodityPlId(tpProductBasisByOld.getCommodityPlId());
						tpProductBasis.setNameId(tpProductBasisByOld.getNameId());

						tpProductBasisMapper.update(tpProductBasis);
						List<TpProductMaterial> tpProductMaterialList = new TpProductMaterial()
								.setProductCode(tpProductBasis.getCode())
								.setType(TpProductMaterialEnum.Type.TP_ProductBasis.value)
								.queryList();
						if(tpProductMaterialList==null || tpProductMaterialList.size()<=0){

							List<TpProductMaterial> tpProductMaterialListByOld = new TpProductMaterial()
									.setProductCode(tpProductBasis.getCode())
									.setType(TpProductMaterialEnum.Type.TP_ProductBasis.value)
									.queryList();
							if(tpProductMaterialListByOld!=null && tpProductMaterialListByOld.size()>0){
								for(TpProductMaterial tpProductMaterialByOld:tpProductMaterialListByOld){
									tpProductMaterialByOld.setProductCode(tpProductBasis.getCode());
									tpProductMaterialMapper.insert(tpProductMaterialByOld);
								}
							}
						}
					}
				}

			}

			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}



	@RequestMapping("/test36")
	@ResponseBody
	public R test36(HttpServletRequest request, HttpServletResponse response,String countMonth
	) {
		logger.info("***********开始***********");
		TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setStatus(1).queryFirst();
		long id = 12;
		TsBatchImportInfo tsBatchImportInfo = new TsBatchImportInfo()
				.setId(id)
				.queryFirst();
		if(tsBatchImportInfo!=null && tsBatchImportInfo.getId()!=null){

			//获取导入的商品库详情数据
			List<TsBatchImportLog> productList = new TsBatchImportLog()
					.setPid(tsBatchImportInfo.getId())
					.setInfoType(TsBatchImportLogEnum.InfoType.TP_ProductBasis.value)
					//.setImportState(TsBatchImportLogEnum.ImportState.NO.value)
					.queryList();

			//导入都结束后 ， 读取导入的Log数据，然后新增数据
			if(productList!=null && productList.size()>0){
				//遍历
				for(TsBatchImportLog productItem:productList){
					String productInfoByStr = productItem.getImportInfo();
					JSONObject productInfo = JSONObject.parseObject(productInfoByStr);

					TpProductBasis tpProductBasis = new TpProductBasis().setVgsBm("GS0422").where("A.Name IS NULL").setLinkIn(productInfo.get("linkIn").toString().trim()).queryFirst();
					TpProductActive tpProductActive = new TpProductActive().setVgsBm("GS0422").where("A.Name IS NULL").setLinkIn(productInfo.get("linkIn").toString().trim()).queryFirst();

					logger.info("***********开始："+tpProductBasis.getCode()+"***********");

					//商品名称
					if(productInfo.get("productName")!=null && !"".equals(productInfo.get("productName").toString().trim())) {
						tpProductBasis.setName(productInfo.get("productName").toString().trim());
						tpProductActive.setName(productInfo.get("productName").toString().trim());
					}

					//商品组合
					if(productInfo.get("productCombination")!=null) {
						tpProductBasis.setCombination(productInfo.get("productCombination").toString().trim());
						tpProductActive.setCombination(productInfo.get("productCombination").toString().trim());
					}

					//新增商品库信息
					tpProductBasisMapper.update(tpProductBasis);
					//新增Listing库信息
					tpProductActiveMapper.update(tpProductActive);

				}

			}


		}

		logger.info("***********完成***********");
		return R.ok();
	}




	@RequestMapping("/test37")
	@ResponseBody
	public R test37(HttpServletRequest request, HttpServletResponse response,String countMonth
	) {
		logger.info("***********开始***********");
		List<TccFbaBoxUpItem> itemList = new TccFbaBoxUpItem().queryList();

		for(TccFbaBoxUpItem item:itemList){
			logger.info("***********开始"+item.getId()+"***********");
			TbSite tbSite  = new TbSite()
					//.addLeftJoin("TP_AmazonRegion B ON B.Code = A.RegionCode") //亚马逊 区域表
					//.addLeftJoin("TB_Site C ON C.RegionCode = A.RegionCode") //站点信息表
					.addLeftJoin("TP_AmazonShop D ON D.SiteId = A.Id") // 店铺信息表
					.addLeftJoin("TCC_Fbaplan E ON E.ShopId = D.Id") //FBA计划单
					.where("E.Bid = '"+item.getBidFbaPlan()+"'")
					.where("A.Status = 1")
					.queryFirst();
			if(tbSite == null || tbSite.getAmazonSalesChannel()==null){
			}else{

				TccFbaPlanItem  tccFbaPlanItem = new TccFbaPlanItem().setId(item.getFbaPlanItemId()).queryFirst();

				item.setGoodsLink("https://www."+ tbSite.getAmazonSalesChannel().trim()+"/dp/"+tccFbaPlanItem.getAsin()+"?ref=myi_title_dp"); //商品链接
				tccFbaBoxUpItemMapper.update(item);
			}
		}




		logger.info("***********完成***********");
		return R.ok();
	}








}
